package com.zhuqian.myapplication

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import androidx.appcompat.widget.AppCompatImageView
import kotlin.math.min


class ScaledImageView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {

    private val matrix = Matrix()
    private val scaleDetector: ScaleGestureDetector? = ScaleGestureDetector(context, ScaleListener())
    private var lastTouchX: Float = 0f
    private var lastTouchY: Float = 0f
    private val cropRect = Rect()
    var isMovingEnabled = false
//    var isScalingMovingEnabled = false


    init {
        scaleType = ScaleType.MATRIX
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        // 设置裁剪矩形的位置和大小
        val cropWidth = w * 0.8f
        val cropHeight = h * 0.8f
        val left = (w - cropWidth) / 2
        val top = (h - cropHeight) / 2
        cropRect.set(left.toInt(), top.toInt(), (left + cropWidth).toInt(), (top + cropHeight).toInt())
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        // 绘制半透明遮罩
        val maskPaint = Paint()
        maskPaint.color = Color.parseColor("#AA000000")
        // 上方遮罩
        canvas.drawRect(0f, 0f, width.toFloat(), cropRect.top.toFloat(), maskPaint)
        // 下方遮罩
        canvas.drawRect(0f, cropRect.bottom.toFloat(), width.toFloat(), height.toFloat(), maskPaint)
        // 左侧遮罩
        canvas.drawRect(0f, cropRect.top.toFloat(), cropRect.left.toFloat(), cropRect.bottom.toFloat(), maskPaint)
        // 右侧遮罩
        canvas.drawRect(
            cropRect.right.toFloat(),
            cropRect.top.toFloat(),
            width.toFloat(),
            cropRect.bottom.toFloat(),
            maskPaint
        )
        // 绘制裁剪矩形
        val paint = Paint()
        paint.color = Color.RED
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = 3f
        canvas.drawRect(cropRect, paint)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
//        if (!isScalingMovingEnabled) return true
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                isMovingEnabled = true  // 记录按下
                // 记录按下的位置
                lastTouchX = event.x
                lastTouchY = event.y
            }

            MotionEvent.ACTION_MOVE -> {
                if (isMovingEnabled) {
                    // 移动时，一直计算偏移，并更新上一次的位置
                    val dx = event.x - lastTouchX
                    val dy = event.y - lastTouchY
                    matrix.postTranslate(dx, dy)
                    imageMatrix = matrix
                    lastTouchX = event.x
                    lastTouchY = event.y
                }
            }
        }
        scaleDetector?.onTouchEvent(event)
        return true
    }

    private inner class ScaleListener : ScaleGestureDetector.SimpleOnScaleGestureListener() {
        override fun onScale(detector: ScaleGestureDetector): Boolean {
            isMovingEnabled = false  // 双指按下有现有顺序，依然会触发单指按下操作，因此这里需要再次将移动标记取消掉
            val scaleFactor = detector.scaleFactor
            // 获取View的中心点
            val centerX = width / 2f
            val centerY = height / 2f
            matrix.postScale(scaleFactor, scaleFactor, centerX, centerY)
            imageMatrix = matrix
            return true
        }
    }

    fun getBitmapFromRect(): Bitmap? {
        val drawable = drawable ?: return null
        val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        val drawableMatrix = imageMatrix
        canvas.concat(drawableMatrix)
        drawable.draw(canvas)

        // 确保 cropRect 不超过 bitmap 的范围
        val rectWidth = Math.min(cropRect.width(), bitmap.width - cropRect.left)
        val rectHeight = Math.min(cropRect.height(), bitmap.height - cropRect.top)
        return Bitmap.createBitmap(bitmap, cropRect.left, cropRect.top, rectWidth, rectHeight)
    }

    override fun setImageBitmap(bm: Bitmap?) {
        bm?.let {
            val min_scale = min(1.0f * width / it.width, 1.0f * height / it.height)

            super.setImageBitmap(bm)
            // 缩放
            matrix.postScale(min_scale, min_scale, 0f, 0f)
            // 移动
            val dx = (width - it.width * min_scale) / 2f
            val dy = (height - it.height * min_scale) / 2f
            matrix.postTranslate(dx, dy)
            imageMatrix = matrix
            // 允许图像触摸移动
//            isScalingMovingEnabled = true
        }
    }

    fun setBitmapOnView(bitmap: Bitmap?) {
        // 设置Bitmap
        matrix.reset()
        imageMatrix = matrix
        setImageBitmap(bitmap)
    }

    fun setBitmapInRect(bitmap: Bitmap) {
        // 设置Bitmap
        setImageBitmap(bitmap)

        // 计算缩放比例和平移距离
        val scaleX = cropRect.width().toFloat() / bitmap.width
        val scaleY = cropRect.height().toFloat() / bitmap.height
        val scale = Math.max(scaleX, scaleY)
        val dx = (cropRect.width() - bitmap.width * scale) / 2f
        val dy = (cropRect.height() - bitmap.height * scale) / 2f

//         更新Matrix
        matrix.reset()
        matrix.postScale(scale, scale)
        matrix.postTranslate(dx + cropRect.left, dy + cropRect.top)
        imageMatrix = matrix


        // 设置禁止移动
//        isScalingMovingEnabled = false
    }
}